package com.mask.kafka.producer;

import org.apache.kafka.clients.producer.*;

import java.util.Properties;

/**
 * producer异步回调
 * @author hx
 * @since 2022/3/15 9:38 下午
 */

public class ProducerCallback {
    public static void main(String[] args) throws InterruptedException {
        Properties properties = new Properties();
        properties.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG,"master:9092");
        properties.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");
        properties.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG,"org.apache.kafka.common.serialization.StringSerializer");

        KafkaProducer<String, String> producer = new KafkaProducer<>(properties);

        for (int i = 0; i < 5; i++) {
            producer.send(new ProducerRecord<>("first", "Melody " + i), new Callback() {
                @Override
                public void onCompletion(RecordMetadata recordMetadata, Exception e) {
                    if (e == null) {
                        System.out.println("主题："+recordMetadata.topic() + "->" + recordMetadata.partition());
                    }else {
                        e.printStackTrace();
                    }
                }
            });

            Thread.sleep(20);

        }
        System.out.println("finish");

        producer.close();
    }
}
